<?php
declare (strict_types=1);

namespace quick\admin;


use app\common\model\SystemAttachmentDisk;
use app\common\model\SystemAttachmentStorage;
use quick\admin\form\Form;
use quick\admin\library\service\UploadService;
use think\facade\Lang;

class QuickPluginService
{
    use AuthorizedToSee;


    /**
     * 应用key 英语标识
     *
     * @var string
     */
    public $app_key = "quick";

    /**
     * @return string
     */
    public function getAppKey()
    {
        return $this->app_key;
    }

    /**
     *
     */
    public function boot()
    {
        Quick::$app_key = $this->getAppKey();
        $this->bootTools();
        $this->loadLang();// 加载语言包
        $this->registerAssets();// 前端资源
        $this->registerResources();// 后端资源
    }


    /**
     * 第三方工具
     * @return array
     */
    public function tools(): array
    {
        return [];
    }


    /**
     *  注册script
     *
     * @return array
     */
    public function script(): array
    {

        return [];
    }


    /**
     * 注册style
     *
     * @return array
     */
    public function style(): array
    {
        return [];
    }


    /**
     * 本地组件路径
     * @return string
     */
    public function viewComponentPath()
    {
        return '';
    }


    /**
     * 渲染组件
     * @return bool
     */
    public function readerComponent()
    {
        if (!$this->viewComponentPath()) {
            return false;
        }

        $config = [
            'view_path' => root_path("plugins/{$this->getAppKey()}/view"),
            'cache_path' => root_path('/runtime/template'),
            'view_suffix' => 'html',
        ];
        $template = new \think\Template($config);
        $template->fetch($this->viewComponentPath());
    }


    /**
     * @return array
     */
    public function resources(): array
    {
        return [];
    }


    /**
     * 注册资源
     */
    public function registerResources()
    {

        $appKey = $this->getAppKey();
        $dir = root_path(str_replace([
            "Plugin",
            '/',
            '\\',
        ], [
            "quick",
            DIRECTORY_SEPARATOR,
            DIRECTORY_SEPARATOR,
        ], static::class));
        $resources = $this->resources();
        Quick::registerResource(function () use ($appKey, $resources, $dir) {
            Quick::resources($appKey, $resources);
            Quick::resourcesIn($appKey, $dir);
        });


    }

    public function loadLang()
    {
        $dir = root_path(str_replace([
            "Plugin",
            '/',
            '\\',
        ], [
            "lang",
            DIRECTORY_SEPARATOR,
            DIRECTORY_SEPARATOR,
        ], static::class));
        $langset = Lang::getLangSet();
        // 加载语言包
        $tempFiles = glob($dir . $langset . '.*');
        $langList = glob($dir . $langset . DIRECTORY_SEPARATOR . '*');
        $tempFiles = array_merge($tempFiles, $langList);
        Lang::load($tempFiles);
    }

    /**
     * 启动加载assets
     *
     */
    public function registerAssets()
    {

        $scripts = $this->script();
        $styles = $this->style();
        $module = $this->getAppKey();
        Quick::registerAssets(function () use ($module, $scripts, $styles) {
            !empty($scripts) && Quick::script($module, $scripts);
            !empty($styles) && Quick::style($module, $styles);
        });

    }


    /**
     *  启动第三方资源工具
     */
    private function bootTools()
    {
        if ($tools = $this->tools()) {
            collect($tools)->each(function (QuickTool $tool) {
                if ($tool->authorizedToSee(request())) {
                    $tool->appKey($this->getAppKey());
                    $tool->boot();
                }
            });
        }
    }


    /**
     * cli命令行及所有请求都会执行，谨慎使用，影响性能一般用于事件监听使用
     */
    public function runBoot()
    {

    }


    /**
     * 分配上传空间key
     * @return string
     */
    public function uploadStorageKey()
    {
        return 'admin';
    }


    /**
     * 获取上传服务
     * @param string|null $type
     * @return UploadService
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function uploadService(?string $type = null): UploadService
    {

        $storageKey = $this->uploadStorageKey();
        $storage = SystemAttachmentStorage::where([
            ['app_key', '=', $storageKey],
            ['is_deleted', '=', 0],
        ])->find();
        if (!$storage) {
            $storage = SystemAttachmentStorage::create(['app_key' => $storageKey, 'is_deleted' => 0]);
        }

        $map = [
            'storage_id' => $storage->id,
            'is_deleted' => 0,
            'status' => 1
        ];

        if($type){
            $map['type'] = $type;
        }

        $disk = SystemAttachmentDisk::where($map)->find();
        if (!$disk) {
            throw new \Exception('上传配置有误，请先配置上传方式');
        }

        /** @var UploadService $uplate */
        $update = UploadService::instance([$disk]);
        $update->pre = $storage->app_key;
        return $update;
    }


    /**
     * 权限key
     * 使用权限key获取第三方驱动配置
     * @return string
     */
    public function authCode(): string
    {
        return '1';
    }


    /**
     * 配置类
     * @return PluginConfigInterface|bool
     */
    public function configForm()
    {
        return false;
    }
}
